/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.controller.func;

import com.je.common.base.DynaBean;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.util.ArrayUtils;
import com.je.common.base.util.MessageUtils;
import com.je.common.base.util.StringUtil;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.service.common.MetaBeanService;
import com.je.meta.service.func.MetaFuncRelyonService;
import com.je.meta.service.table.MetaResFieldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/je/meta/resField")
public class ResFieldController extends AbstractPlatformController {

    @Autowired
    private MetaResFieldService resFieldService;
    @Autowired
    private MetaFuncRelyonService funcRelyonService;
    @Autowired
    private MetaBeanService metaBeanService;

    /**
     * @param param
     */
    @RequestMapping(value = "/doSync", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doSync(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = new DynaBean();
        dynaBean.setStr("RESOURCEFIELD_FUNCINFO_ID", getStringParameter(request, "RESOURCEFIELD_FUNCINFO_ID"));
        dynaBean.setStr("RESOURCEFIELD_PLAN_ID", getStringParameter(request, "RESOURCEFIELD_PLAN_ID"));
        dynaBean.setStr("RESOURCECOLUMN_PLAN_ID", getStringParameter(request, "RESOURCECOLUMN_PLAN_ID"));
        //同步
        resFieldService.doSync(dynaBean);
        //软连接功能处理，此处目的不明确，先注释
        //funcRelyonService.doSyncColumn(dynaBean.getStr("RESOURCEFIELD_FUNCINFO_ID"));
        return BaseRespResult.successResult("同步成功!");
    }

    /**
     * @param param
     */
    @RequestMapping(value = "/doSave", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Override
    public BaseRespResult doSave(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        //判断指定类型可以添加
        String xtype = dynaBean.getStr("RESOURCEFIELD_XTYPE");
        if (!ArrayUtils.contains(new String[]{"fieldset", "displayfield", "chartfield", "childfuncfield"}, xtype)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("function.field.type.error"));
        }
        //构建字段默认信息
        resFieldService.buildDefault(dynaBean);
        /*String wheresql = " RESOURCEFIELD_FUNCINFO_ID=" + "'" + dynaBean.getStr("RESOURCEFIELD_FUNCINFO_ID") + "'";
        if (StringUtil.isNotEmpty(dynaBean.getStr("RESOURCEFIELD_PLAN_ID"))) {
            wheresql = wheresql + " AND RESOURCEFIELD_PLAN_ID=" + "'" + dynaBean.getStr("RESOURCEFIELD_PLAN_ID") + "'";
        }*/
        DynaBean inserted = commonService.doSave(dynaBean);
        //处理软链接
        funcRelyonService.doSave("JE_CORE_RESOURCEFIELD", inserted.getStr("RESOURCEFIELD_FUNCINFO_ID"), inserted);
        return BaseRespResult.successResult(dynaBean);
    }

    /**
     * @param param
     */
    @RequestMapping(value = "/doUpdateList", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Override
    public BaseRespResult doUpdateList(BaseMethodArgument param, HttpServletRequest request) {
        String tableCode = "JE_CORE_RESOURCEFIELD";
        String strData = param.getStrData();
        List<DynaBean> updateList = new ArrayList<DynaBean>();
        List<DynaBean> lists = metaBeanService.buildUpdateList(strData, tableCode);
        for (DynaBean bean : lists) {
            String pkValue = bean.getPkValue();
            if (StringUtil.isNotEmpty(pkValue)) {
                //使用字段的更新操作     如果该字段为只读，则更新列表不可编辑
                bean = resFieldService.updateField(bean);
            } else {
                metaService.insert(bean);
            }
            updateList.add(bean);
        }
        if (!"JE_CORE_RESOURCEFIELD_C".equals(tableCode)) {
            //处理软连接
            funcRelyonService.doUpdateList("JE_CORE_RESOURCEFIELD", "", updateList);
        }
        return BaseRespResult.successResult(updateList.size() + "条记录被更新!");
    }

    /**
     * TODO未处理
     *
     * @param param
     */
    @RequestMapping(value = "/doUpdate", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Override
    public BaseRespResult doUpdate(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String tableCode = param.getTableCode();
        DynaBean oldField = metaService.selectOneByPk(tableCode, dynaBean.getStr("JE_CORE_RESOURCEFIELD_ID"));
        commonService.buildModelModifyInfo(dynaBean);
        DynaBean updated = resFieldService.updateField(dynaBean);
        funcRelyonService.doUpdate("JE_CORE_RESOURCEFIELD", updated.getStr("RESOURCEFIELD_FUNCINFO_ID"), funcRelyonService.getUpdateBean("JE_CORE_RESOURCEFIELD", updated, oldField));
        return BaseRespResult.successResult(updated);
    }

    /**
     * TODO未处理
     *
     * @param param
     */
    @RequestMapping(value = "/doRemove", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Override
    public BaseRespResult doRemove(BaseMethodArgument param, HttpServletRequest request) {
        String ids = param.getIds();
        funcRelyonService.doRemove("JE_CORE_RESOURCEFIELD", null, ids, null);
        int delNum =resFieldService.doRemove(ids);
        return BaseRespResult.successResult(delNum + "条记录被删除!");
    }

    /**
     * TODO未处理
     *
     * @param param
     */
    @RequestMapping(value = "/updateLabelPosition", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult updateLabelPosition(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean =(DynaBean) request.getAttribute("dynaBean");
        String RESOURCEFIELD_PLAN_ID =  dynaBean.getStr("RESOURCEFIELD_PLAN_ID");
        ConditionsWrapper conditionsWrapper = ConditionsWrapper.builder();
        if(StringUtil.isNotEmpty(RESOURCEFIELD_PLAN_ID)){
            conditionsWrapper.eq("RESOURCEFIELD_PLAN_ID",RESOURCEFIELD_PLAN_ID);
        }
        conditionsWrapper.eq("RESOURCEFIELD_FUNCINFO_ID",dynaBean.getStr("RESOURCEFIELD_FUNCINFO_ID"));

        DynaBean update = new DynaBean("JE_CORE_RESOURCEFIELD",false);
        update.setStr("RESOURCEFIELD_LABELALIGN",dynaBean.getStr("RESOURCEFIELD_LABELALIGN"));
        metaService.update(update,conditionsWrapper);
        return BaseRespResult.successResult(MessageUtils.getMessage("common.operation.success"));
    }

}
